package com.shop.ex.handle;

import com.shop.ex.ShoppingException;
import com.shop.po.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolationException;

/**
 * @author 'banxia'
 * @version 1.0
 * @description TODO
 * @date 2023/2/21 16:15
 */
@ControllerAdvice
@Slf4j
public class RuntimeExceptionHandle {

    @ExceptionHandler(ConstraintViolationException.class)
    ResponseEntity<String> handleConstraintViolationException(ConstraintViolationException e) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
    }

    //自定义异常的捕获与返回
    @ResponseBody
    @ExceptionHandler(ShoppingException.class)
    public R ShoppingExceptionHandle(Exception e){
        displayLog(e);
        return R.error(e.getMessage());
    }

    //名称唯一性异常
    @ResponseBody
    @ExceptionHandler(DataAccessException.class)
    public R uniqueException(DataAccessException e) {
        displayLog(e);
        if (e.getMessage().indexOf("Duplicate entry") != -1) {
            int startIndex=e.getMessage().indexOf("Duplicate entry ")+15;
            int endIndex=e.getMessage().indexOf("for key '");
            String message=e.getMessage().substring(startIndex,endIndex);
//            String[] messages = e.getMessage().split(" ");
//            String message = messages[2];
            return R.error().message(message + "已经存在，请换一个");
        } else {
            return R.error().message("未知异常");
        }
    }

    //全局异常
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public R ExceptionHandle(Exception e){
        displayLog(e);
        e.printStackTrace();
        return R.error("全局异常");
    }

    private void displayLog(Exception e){
        log.error("====================出异常了====================");
        log.error("message:"+e.getMessage());
        log.error("class:"+e.getClass());
        log.error("====================出异常了====================");
    }
}
